<?php
class db{
	public $conn = false;
	private $app;
	
	public function __construct(){
		global $app;
		$str = "mysql:host=".DBHOST.";dbname=".DBNAME;
		try{
			$this->conn = new PDO($str, DBUSER, DBPASS);
			$this->conn->exec("set names utf8");
		}catch(PDOException $e){
			print_r($e->errorInfo());
		}
		$app->{"db"} =& $this;
		$this->app =& $app;
	}
	
	/**
	 * @param string $sql
	 */
	public function execute($sql){
		return $this->conn->exec($sql);
	}
	
	/**
	 * 執行SQL語法並fetchAll
	 * @param string $sql
	 */
	public function getAll($sql){
		try{
			$res = $this->conn->prepare($sql);
			$res->execute();
		}catch(PDOException $e){
			app_die(implode($e->errorInfo()));
		}
		return $res->fetchAll();
	}
	
	/**
	 * 執行類似SQL語法多次，替代使用迴圈執行
	 * @param string $prepare
	 * @param array $keys
	 * @param array $values
	 */
	public function multi($prepare, $keys, $values){
		$res = $this->conn->prepare($prepare);
		if(is_array($values)){
			foreach($values as $value){
				foreach($keys as $val)
					$execute[$val] = $value;
				$res->execute($execute);
			}
		}
	}
	
	/**
	 * 執行SELECT語法
	 * @param string $table
	 * @param string $column
	 * @param string $other
	 */
	public function select($table, $column = "*", $other = ""){
		if(empty($this->app->table[$table]))
			app_die("找不到 `{$table}` 表格");
		if(empty($column))
			$column = "*";
		try{
			$res = $this->conn->prepare("SELECT {$column} FROM `{$this->app->table[$table]}` {$other}");
			$res->execute();
		}catch(PDOException $e){
			app_die(implode($e->errorInfo()));
		}
		return $res->fetchAll();
	}
	
	/**
	 * 新增一筆或多筆資料
	 * @param string $table
	 * @param array $column
	 * @param array $value
	 * @param boolean $multi - 是否新增多筆資料
	 */
	public function insert($table, $column, $value, $multi = false){
		if(empty($this->app->table[$table]))
			app_die("找不到 `{$table}` 表格");
		foreach($column as $key => $col){
			$values .= ($key==0? "": ", ")."?";
			$columns .= ($key==0? "": ", ")."`{$col}`";
		}
		try{
			$res = $this->conn->prepare("INSERT INTO `{$this->app->table[$table]}` ({$columns}) VALUES({$values})");
			if($multi){
				foreach($value as $val){
					$res->execute($val);
				}
			}else{
				$res->execute($value);
			}
		}catch(PDOException $e){
			app_die(implode($e->errorInfo()));
		}
		return true;
	}
	
	/**
	 * 更新資料
	 * @param string $table
	 * @param array $column
	 * @param array $value
	 * @param string $where
	 */
	public function update($table, $column, $value, $where){
		if(empty($this->app->table[$table]))
			app_die("找不到 `{$table}` 表格");
		foreach($column as $i => $col){
			$update .= ($i==0? "":", ")."`{$col}`='{$value[$i]}'";
		}
		try{
			$res = $this->conn->prepare("UPDATE `{$this->app->table[$table]}` SET {$update} WHERE {$where}");
			$res->execute();
		}catch(PDOException $e){
			app_die(implode($e->errorInfo()));
		}
		return true;
	}
}
?>